<template>
  <div class="wxstatistics-list">
    <Row type="flex" justify="space-between" class="wxstatistics-list-edit">
      <Form class="from" :model="searchObj" ref="search" label-position="left" inline>
        <FormItem :label-width="50">
          <div slot="label" style="transform: translateX(12px);">时间：</div>
          <datePickerYmd
            @on-change="search"
            :selectDateType.sync="selectDateType "
            :dateOption="dateOption"
            :dataType='dataType'
            v-model="timeDate"
          ></datePickerYmd>
        </FormItem>

        <!-- <FormItem :label-width="75" >
          <div slot="label" style="transform: translateX(12px);">门店名称：</div>
          <Select
            class="select-shop-item"
            @on-change="search"
            v-model="searchObj.shopId"
            multiple
            filterable
            :max-tag-count="1"
            :max-tag-placeholder="maxTagPlaceholder"
            style="width:180px"
          >
            <Option
              v-for="item in shopList"
              :value="item.shopId"
              :key="item.shopId"
            >{{ item.shopName }}</Option>
          </Select>
        </FormItem>-->
        <FormItem :label-width="72">
          <div slot="label" style="transform: translateX(12px);">门店名称：</div>
          <!-- <vueTreeselectShop
            :shopList.sync="searchObj.shopId"
            @id-change="search"
            permissionCode="moms:report:weixinanalytics"
            v-model="ShopValue"
          ></vueTreeselectShop> -->
          <!-- <vueTreeselectChoice
              :multiple="true"
              ref="vueTreeselectChoice"
              @input="handleShop"
              @on-api-finish="apiFinish"
              permissionCode="moms:report:weixinanalytics"
              v-model="ShopValue"
            ></vueTreeselectChoice> -->
          <vueTreeselectChoice
            :max-tag-count='1'
            componentsType='iselect'
            :filterable="true"
            @on-change="handleShop"
            permissionCode="moms:report:weixinanalytics"
            v-model="searchObj.shopId"
          ></vueTreeselectChoice>
        </FormItem>
        <FormItem>
          <Button type="primary" class="coinrevenue-btn" @click="search('search')">查询</Button>
        </FormItem>
      </Form>
    </Row>
    <!-- :loading="isloading" -->
    <Table
      :loading="isloading"
      border
      class="table-list"
      stripe
      ref="rowSpanTable"
      :columns="columns"
      :data="resData"
    ></Table>
    <!-- <div class="page-box" style="margin-top: 20px">
      <Page
        :total="total"
        ref="pages"
        :current.sync="searchObj.pageIndex"
        :page-size="searchObj.limit"
        @on-change="handlePage"
        @on-page-size-change="handlePageSize"
        show-sizer
        show-total
      />
    </div> -->
  </div>
</template>
<script>
// import { rowSpanTable, formatRowspanData } from '@/libs/rowspan'
import { shopWxStatistics } from '@/api/report/shop'

import dayjs from 'dayjs'
import { formatAmount } from '@/libs/tools'
import datePickerYmd from '@/components/date-picker-ymd/date-picker-ymd.vue'
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
export default {
  name: 'report_shop_wxstatistics',
  components: {
    datePickerYmd,
    vueTreeselectChoice
  },
  data () {
    return {
      shopList: [],
      total: 0,
      isloading: false,
      bottonActive: '日',
      timeDate: [dayjs().format('YYYY-MM-DD 00:00:00'), dayjs().format('YYYY-MM-DD 00:00:00')],
      selectDateType: 'date',
      dataType: [{ key: 'date', value: '日' }, { key: 'month', value: '月' }, { key: 'year', value: '年' }],
      searchObj: {
        offset: 0,
        pageIndex: 1,
        limit: 10,
        dateTimes: new Date(),
        dateRange: [new Date(), new Date()],
        shopId: ''
      },
      dateOption: {
        disabledDate: date => {
          return dayjs(date).isAfter(dayjs(new Date()))
        }
      },
      columns: [
        { title: '门店', key: 'shopName', align: 'center', width: 185, fixed: 'left' },
        {
          title: '',
          align: 'center',

          children: [
            { title: '销量(笔)', key: 'saleNum0', align: 'center' },
            { title: '取币数(枚)', key: 'withdrawNum0', align: 'center' },
            { title: '新增会员数(人)', key: 'memberAddNum0', align: 'center' },
            { title: '代金券使用数量(张)', key: 'couponUseNum0', align: 'center' },
            {
              title: '代金券抵用金额(元)',
              key: 'couponUseAmount0',
              align: 'center',
              render: (h, params) => {
                return h('span', formatAmount(params.row.couponUseAmount0))
              }
            },
            { title: '总金额(元)', key: 'totalAmount0', align: 'center' }
          ]
        },
        {
          title: '',
          align: 'center',

          children: [
            { title: '销量(笔)', key: 'saleNum1', align: 'center' },
            { title: '取币数(枚)', key: 'withdrawNum1', align: 'center' },
            { title: '新增会员数(人)', key: 'memberAddNum1', align: 'center' },
            { title: '代金券使用数量(张)', key: 'couponUseNum1', align: 'center' },
            {
              title: '代金券抵用金额(元)',
              key: 'couponUseAmount1',
              align: 'center',
              render: (h, params) => {
                return h('span', formatAmount(params.row.couponUseAmount1))
              }
            },
            { title: '总金额(元)', key: 'totalAmount1', align: 'center' }
          ]
        }
      ],
      resData: []
    }
  },
  computed: {
    dateFormat () {
      if (this.bottonActive === '日') return 'yyyy-MM-dd'
      return 'yyyy-MM'
    },
    dateType () {
      if (this.bottonActive === '日') return 'date'
      return 'month'
    },
    startDate () {
      return this.timeDate[0]
    },
    endDate () {
      if (this.selectDateType === 'daterange') {
        return dayjs(this.timeDate[1])
          .add(1, 'day')
          .format('YYYY-MM-DD 00:00:00')
      }
      return this.timeDate[1]
    },
    columnTimes () {
      return [this.startDate, this.endDate]
    }
  },

  created () {
    this.$set(this.columns[1], 'title', dayjs(this.columnTimes[1]).format('YYYY-MM-DD'))
    this.$set(this.columns[2], 'title', dayjs(this.columnTimes[0]).format('YYYY-MM-DD'))
    if (this.$store.state.user.orgType === 1) {
      this.searchObj.shopId = this.$store.state.user.orgId
      this.shopWxStatistics()
    }
  },
  mounted () {
    // this.getShopList()
  },
  methods: {
    async handleShop () {
      this.searchObj.offset = 0
      this.searchObj.pageIndex = 1
      this.search()
    },
    // apiFinish (isId) {
    //   if (isId) this.ShopValue = [this.$store.state.user.orgId]
    // },
    handlePage (val) {
      this.searchObj.offset = (val - 1) * this.searchObj.limit
      this.shopWxStatistics()
    },
    handlePageSize (val) {
      this.searchObj.limit = val
      this.searchObj.offset = 0
      this.shopWxStatistics()
    },
    // 表单校验
    validateSearchForm (data = this.searchObj) {
      if (!dayjs(this.startDate).isValid()) return '请选择时间'
      if (!data.shopId) return '请选择门店'
      return true
    },
    async shopWxStatistics (
      params = {
        merchantId: this.$store.state.user.merchantId,
        shopIds: [this.searchObj.shopId],
        startDate: this.startDate,
        endDate: this.endDate,
        limit: this.searchObj.limit,
        offset: this.searchObj.offset
      }
    ) {
      if (this.validateSearchForm() !== true) return this.$Message.error(`${this.validateSearchForm()}`)
      this.isloading = true

      try {
        const res = await shopWxStatistics(params)
        this.isloading = false
        if (res.data.status !== 200) return this.$Message.error(`${res.data.error}`)
        const data = res.data.data || []
        this.total = res.data.totalCount
        // 如果没有数据设置表格时间
        if (!data.length) {
          this.$set(this.columns[1], 'title', dayjs(this.columnTimes[1]).format('YYYY-MM-DD'))
          this.$set(this.columns[2], 'title', dayjs(this.columnTimes[0]).format('YYYY-MM-DD'))
        }
        this.resData = data.map((item, index) => {
          let obj = { shopName: item['shopName'] }

          // 添加时间
          item.itemVOs.map((list, j) => {
            this.$set(this.columns[j + 1], 'title', list.statDate)

            Object.keys(list).map(key => {
              obj[`${key}${j}`] = list[key]
            })
          })

          // Object.keys(item).map(list => {
          //   obj[`${list}${index}`] = item[list]
          // })
          return obj
        })

        // this.resData = [Object.assign({}, { shopName: data.shopName }, obj)]
      } catch (error) {
        this.isloading = false
        this.$Message.error(`${error}`)
      }
    },

    search (name) {
      this.searchObj.offset = 0
      this.searchObj.pageIndex = 1
      this.shopWxStatistics()
    }
  }
}
</script>
<style lang="less" scoped>
.wxstatistics-list {
  .from {
    margin-top: 24px;
  }
  .wxstatistics-list-edit {
    padding-left: 20px;
  }
  .button_active {
    border: 1px solid #2d8cf0;
  }
}
</style>
<style lang="less">
.wxstatistics-list {
  thead tr th {
    border-left: 1px solid #e8eaec;
  }
  thead tr:first-of-type th:first-of-type {
    border-left: none;
  }
}
.select-shop-item {
  height: 35px;
  width: 210px;
  .ivu-select-selection {
    height: 35px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .ivu-tag {
    max-width: 100px;
  }
}
</style>
